// 商家联合申请
(function() {
	var db = require("../db/index");
	var config = require("../_include/config");
	var db_table_name = config.dbname.assshop;
	var db_id_prefix = config.dbIdPrefix.assshop;
	var BusCon = require("../bus/_con");
	var helper = require("../_include/helper");

	//构造函数
	var _con = function(my_bus_id, acc_bus_id) {
		var self = this;
		//ID编号
		self._id = db_id_prefix + Math.random().toString(16).substr(2) + (+new Date).toString(16);
		//所属的商家
		self.my_bus_id = my_bus_id;
		//申请联合的商家
		self.acc_bus_id = acc_bus_id;
		//生成不重复的申请码
		do {
			self.vcode = Math.random().toString().substr(2, 4);
		} while (
			db.find_one(db_table_name, {
				vcode: self.vcode
			})
		)

		db.insert(db_table_name, self);
		console.log("创建了一个商家联合申请：", self.vcode);
	};
	//PS:模块的暴露放在require skill前面，因为二者互相依赖
	module.exports = _con;
	//技能
	_con.prototype = require("./skill");

	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		return _con.getInstance(result);
	};
	_con.getInstance = function(obj) {
		if (obj) {
			obj.__proto__ = _con.prototype;
		}
		return obj;
	};
	_con.getByVcode = function(vcode) {
		var obj = db.find_one(db_table_name, {
			vcode: vcode
		});
		return _con.getInstance(obj);
	};
	_con.build = function(my_bus_id, acc_bus_id) {
		var obj = db.find_one(db_table_name, {
			my_bus_id: my_bus_id,
			acc_bus_id: acc_bus_id
		});
		if (obj) {
			return _con.getInstance(obj)
		} else {
			return new _con(my_bus_id, acc_bus_id);
		}
	};
	_con.getByMyBusId = function(my_bus_id) {
		return db.find_list(db_table_name, {
			my_bus_id: my_bus_id
		}).map(function(obj) {
			return _con.getInstance(obj)
		});
	}
}());